package org.soenea.doitall.domain.model.person.data;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.dsrg.soenea.service.threadLocal.DbRegistry;

public abstract class PersonTDG {
	public static final String BASE_NAME = "user";
	public static final String TABLE = DbRegistry.getTablePrefix()+BASE_NAME;
	public static final String INSERT = "INSERT INTO " + TABLE + " (userID,version,userName,firstName,lastName,password,groupNum) VALUES (?,?,?,?,?,?,?);";
	// FIXME: UPDATE query is not complete
	public static final String UPDATE = "UPDATE " + TABLE + " AS p set p.groupNum=?, p.version=p.version+1 WHERE p.userID=? AND p.version=?;";
	public static final String DELETE = "DELETE FROM " + TABLE + " WHERE userID=? AND version=?;";
	public static final long NO_GROUP_ID = 0;
	public static final String userID = "userID";
	
	public static void insert(long id, long version, String userName, String firstName, String lastName, String password, int groupNum) throws SQLException {
		PreparedStatement ps = DbRegistry.getDbConnection().prepareStatement(INSERT);
		ps.setLong(1, id);
		ps.setLong(2, version);
		ps.setString(3, userName);
		ps.setString(4, firstName);
		ps.setString(5, lastName);
		ps.setString(6, password);
		ps.setInt(7, groupNum);
		ps.executeUpdate();
		ps.close();
	}

	public static int update(long id, long version, int groupNum) throws SQLException {
		PreparedStatement ps = DbRegistry.getDbConnection().prepareStatement(UPDATE);
		ps.setInt(1, groupNum);
		ps.setLong(2, id);
		ps.setLong(3, version);		
		int count = ps.executeUpdate();
		ps.close();
		return count;
	}

	public static int delete(long id, long version) throws SQLException {
		PreparedStatement ps = DbRegistry.getDbConnection().prepareStatement(DELETE);
		ps.setLong(1, id);
		ps.setLong(2, version);
		int count = ps.executeUpdate();
		ps.close();
		return count;
	}
}
